package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.Service;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * DOCUMENT ME!
 *
 * @author Viktar Liaskovich
 */
public class ServiceDao extends BaseDaoObject<Service> {
    public Service getByKey(Serializable key) {
        return (Service) getHibernateTemplate().get(Service.class, key);
    }

    public Service getServiceByName(final String service, final String username) {
        return (Service) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                return session.createQuery(
                        "select service from Service service, Login login "
                                + "where login.login = :username and service.location = login.location and service.name = :servName")
                        .setParameter("username", username, Hibernate.STRING)
                        .setParameter("servName", service, Hibernate.STRING).list().get(0);
            }
        });
    }

    public Set<Service> getServiceByCriteria(final String value, final String employeeKey) {
        return (Set<Service>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                List<Service> result = session.createQuery("select s2e.service from Service2Employee s2e where " +
                        "s2e.employee.id = :emplKey and s2e.service.name like :name")
                        .setParameter("emplKey", Long.valueOf(employeeKey), Hibernate.LONG)
                        .setParameter("name", "%"+value+"%", Hibernate.STRING)
                        .list();
                return ((result == null) || result.isEmpty())
                        ? new HashSet<Service>() : new HashSet<Service>(result);
            }
        });
    }
}
